/* bucket.c - The routines for playing with hash buckets. */

/*  GNU DBM  - DataBase Manager (database subroutines) by Philip A. Nelson
    Copyright (C) 1989  Free Software Foundation, Inc.

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    You may contact the author by:
       e-mail:  phil@wwu.edu
      us-mail:  Philip A. Nelson
                Computer Science Department
                Western Washington University
                Bellingham, WA 98226
        phone:  (206) 676-3035

*************************************************************************/

#include "gdbm.h"
#include "extern.h"
#include "gdbmutils.h"

#include <stdio.h>

/* Initializing a new hash buckets sets all bucket entries to -1 hash value. */
void _dbm_new_bucket(dbm_file_info * dbf, hash_bucket * bucket, int bits)
{
	int index;

	/* Set the information fields first. */
	bucket->bucket_bits = bits;
	bucket->count = 0;


	/* Initialize all bucket elements. */
	for (index = 0; index < dbf->header.bucket_elems; index++)
		bucket->h_table[index].hash_value = -1;
}



/* Get a hash bucket into memory.  The top bits of HASH_VALUE are used to
   index the hash directory.  If it is already there, do no read. */
int _dbm_get_bucket(dbm_file_info * dbf, int hash_value)
{
	int bucket_adr;		/* The address of the correct hash bucket.  */
	int num_bytes;		/* The number of bytes read. */

	dbf->bucket_dir = hash_value >> (31 - dbf->header.dir_bits);
	bucket_adr = dbf->dir[dbf->bucket_dir];
	if (dbf->bucket_adr != bucket_adr)
	{
		num_bytes = fseek(dbf->desc, bucket_adr, SEEK_SET);
		if (num_bytes != 0)
			_dbm_fatal(dbf, "seek error");
		num_bytes = fread(dbf->bucket, 1, dbf->header.bucket_size, dbf->desc);
		if (num_bytes != dbf->header.bucket_size)
			_dbm_fatal(dbf, "read error");
		dbf->bucket_adr = bucket_adr;
	}

	return TRUE;
}
